﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Crank.Core
{
    class DollarExpadingModelTransformer : IModelTransformer
    {
        #region IModelTransformer Members

        public void ApplyTransform(DataModel target)
        {
            if (target.Entities.ContainsKey("$"))
            {
                var all = target.GetEntityByName("$");
                target.Entities.Remove("$");
                foreach (var att in all.Attributes)
                {
                    foreach (var entity in target.Entities.Values)
                    {
                        entity.Attributes.Add(new AttributeDef(att));
                    }
                }

                var removeLinks = new List<LinkDef>();
                var newLinks = new List<LinkDef>();

                foreach (var link in target.Links.Where(l => l.LHS.Name == "$"))
                {
                    foreach (var entity in target.Entities.Values.Where(e => e != link.RHS))
                    {
                        LinkDef newLink = new LinkDef(link);
                        newLink.LHS = entity;
                        newLinks.Add(newLink);
                    }
                    removeLinks.Add(link);
                }
                foreach (var link in target.Links.Where(l => l.RHS.Name == "$"))
                {
                    foreach (var entity in target.Entities.Values.Where( e => e != link.LHS ))
                    {
                        LinkDef newLink = new LinkDef(link);
                        newLink.RHS = entity;
                        newLinks.Add(newLink);
                    }
                    removeLinks.Add(link);
                }

                foreach (var link in removeLinks)
                   target.Links.Remove(link);
                foreach (var link in newLinks)
                    target.Links.Add(link);
            }
        }

        #endregion
    }
}
